package com.eastfair.messagecenter.script.sms.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eastfair.core.httpClient.PostHttpClient;
import com.eastfair.messagecenter.domain.sms.SmsParam;
import com.eastfair.messagecenter.domain.sms.SmsRecord;
import com.eastfair.messagecenter.script.sms.BaseSmsScript;
import com.eastfair.messagecenter.script.sms.SmsScript;
import com.eastfair.messagecenter.script.sms.SmsScriptHandler;
import com.eastfair.messagecenter.service.MsgServiceService;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author ligang
 * @date 2022年5月23日
 * 企业信使平台接入短信
 */
@Slf4j
@SmsScriptHandler("XmSmsScript")
public class XmSmsScript extends BaseSmsScript implements SmsScript {

    @Value("${xmsx.url}")
    private String url;

    @Value("${xmsx.account}")
    private String account;

    @Value("${xmsx.password}")
    private String password;

    @Value("${xmsx.appId}")
    private String appId;

    @Value("${xmsx.appKey}")
    private String appKey;


    @Override
    public List<SmsRecord> send(SmsParam smsParam) {
        List<SmsRecord> smsRecordList = new ArrayList<>();
        SmsRecord smsRecord = new SmsRecord();
        smsRecord.setMobiles(new ArrayList(smsParam.getMobiles()));
        smsRecord.setMsgIds(smsParam.getMsgIds());
        smsRecord.setSendDate(LocalDateTime.now());
        smsRecord.setMsgContent(smsParam.getContent());
//        log.info("发送消息成功：" + JSON.toJSONString(smsRecord));

        /*
        http://10.11.80.151/io/guomao__io.service.message/south/message/operation
        {
            "account": "gmhz",
                "password": "gmhz@123",
                "action": "send",
                "mobile": "13031187020",
                "content": "消息测试",
                "sendTime": "2023-01-10 19:00:00",
                "extno": ""
        }

      headers

      X-HW-ID   guomao__io.message.send_xmgm
      X-HW-APPKEY   5sQ+n#7T%kh!wpX-/$F0d-eIeGA.%.6QzC!#465T1@k%0SKp/Gd4GzKv2wW2J202



      result:
        {
            "retCode": 0,
            "retJSON": {
                "fun": {
                    "returnsms": {
                        "returnstatus": "Success",
                        "message": "ok",
                        "remainpoint": 1760,
                        "taskID": 5202150,
                        "successCounts": 1
                    }
                }
            }
        }

        */


        try {

            StringBuilder mobileStr = new StringBuilder();
            for (String s : smsParam.getMobiles()) {
                mobileStr.append(s);
                mobileStr.append(",");
            }
            ;
            String smsUrl = url;
            JSONObject params = new JSONObject();
            params.put("account", account);
            params.put("password", password);
            params.put("action", "send");
            params.put("phones", mobileStr.substring(0, mobileStr.length() - 1));
//            params.put("content", smsParam.getContent());
            params.put("content", "【国贸会展】"+smsParam.getContent());
            String timeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            params.put("sendTime", timeStr);

            //header头
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("X-HW-ID", appId);
            headerMap.put("X-HW-APPKEY", appKey);
            log.info("xmSms send is execute  url:{} , params: {} , header : {}", url, JSON.toJSONString(params), JSON.toJSONString(headerMap));
            String result = PostHttpClient.postForm(url, params, headerMap);
            log.info("result is {}", result);
            smsRecord.setReportContent(result);
            //{"retCode":0,"retJSON":{"fun":{"returnsms":{"returnstatus":"Success","message":"ok","remainpoint":1950,"taskID":5264994,"successCounts":1}}}}

            /**
             * {
             *     "retCode": 0,
             *     "retJSON": {
             *         "fun": {
             *             "result": "0",
             *             "desc": "成功",
             *             "timestamp": "20230616094728778",
             *             "msgid": "876401703052668955"
             *         }
             *     }
             * }
             */

            JSONObject jsonObject = JSONObject.parseObject(result);
//            Map<String, Object> resultMap = XmlUtil.xmlToMap(result);
            if ("0".equals(jsonObject.getJSONObject("retJSON").getJSONObject("fun").getString("result"))) {
                //成功  回执单
                smsRecord.setIsSuccess(true);
            } else {
                //失败
                smsRecord.setIsSuccess(false);
            }
            smsRecordList.add(smsRecord);
            return smsRecordList;
        } catch (Exception e) {
            log.error("YunPianSmsScript#send fail:{},params:{}", Throwables.getStackTraceAsString(e), JSON.toJSONString(smsParam));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("exception", Throwables.getStackTraceAsString(e));
            jsonObject.put("smsParam", JSON.toJSONString(smsParam));
            jsonObject.put("postResult", smsRecord.getReportContent());
            smsRecord.setReportContent(jsonObject.toJSONString());
            smsRecord.setIsSuccess(false);
            smsRecordList.add(smsRecord);
            return smsRecordList;
        }

    }

    public static void main(String[] args) {
//        String url = "http://193.112.6.53:8088/sms.aspx?action=send&userid=123&account=gmhz&password=gmhz@123&mobile=13031187020&content=短信内容";
//        JSONObject params = new JSONObject();
////        params.put("userid", 123);
////        params.put("account", "gmhz");
////        params.put("password", "gmhz@123");
////        params.put("mobile", "13031187020");
////        params.put("content","短信内容");
////        params.put("action", "send");
//        String result = PostHttpClient.postForm(url, params);

//        System.out.println(result);


        JSONObject jsonObject = JSONObject.parseObject("{\"retCode\":0,\"retJSON\":{\"fun\":{\"returnsms\":{\"returnstatus\":\"Success\",\"message\":\"ok\",\"remainpoint\":1950,\"taskID\":5264994,\"successCounts\":1}}}}");

        System.out.println(jsonObject.getJSONObject("retJSON").getJSONObject("fun").getJSONObject("returnsms").get("returnstatus"));

    }
}

